//
//  AppDelegate+GTPush.m
//  ZCJZ
//
//  Created by sujeking on 2019/9/18.
//  Copyright © 2019 jeking. All rights reserved.
//

#import "AppDelegate+GTPush.h"
#import <MJExtension.h>
static NSString *GTAppId = @"IyqHj6UUMl5YE6T82yyKd6";
static NSString *GTAppSecret = @"rlgAiv32eg8pLAVEd3q6L8";
static NSString *GTAppKey = @"MYeQaMmxGU9uBCHNqHJE74";


@implementation AppDelegate (GTPush)

- (void)configGTPushWithOption:(NSDictionary *)launchOptions {
    [GeTuiSdk startSdkWithAppId:GTAppId appKey:GTAppKey appSecret:GTAppSecret delegate:self];
    [self registerRemoteNotification];
}

/** 注册 APNs */
- (void)registerRemoteNotification {
    
    CGFloat systemVersion = [[UIDevice currentDevice].systemVersion floatValue];
    
    if (systemVersion >= 10.0) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
            if (!error) {
                NSLog(@"request authorization succeeded!");
            }
        }];
        
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    } else if (systemVersion >= 8.0 && systemVersion < 10) {
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    } else {
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
                                                                       UIRemoteNotificationTypeSound |
                                                                       UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    }
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [GeTuiSdk registerDeviceTokenData:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"注册APNS 失败:%@",error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    [GeTuiSdk handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
    completionHandler(UNNotificationPresentationOptionAlert|UNNotificationPresentationOptionSound);;
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}


/** SDK收到透传消息回调 */
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
    
    // 收到个推消息
    NSString *payloadMsg = nil;
    if (payloadData) {
        payloadMsg = [[NSString alloc] initWithBytes:payloadData.bytes
                                              length:payloadData.length
                                            encoding:NSUTF8StringEncoding];
        
        NSDictionary *dict = [payloadMsg mj_JSONObject];
        if (!offLine) { //在线
            NSString *type = [dict valueForKey:@"type"];
            if ([type isEqualToString:@"link"]) {
                NSString *content = [dict valueForKey:@"content"];
                NSString *title = [dict valueForKey:@"title"];
//                ZCWebVC *vc = [[ZCWebVC alloc] init];
//                vc.remotePath = content;
//                vc.navTitle = title;
//                [[self visibleViewController].navigationController pushViewController:vc animated:YES];
            }
            
        } else {
            
        }
    }
}

// MARK: - Other

- (UIViewController *)visibleViewController {
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;;
    return [self getVisibleViewControllerFrom:rootViewController];
}

- (UIViewController *)getVisibleViewControllerFrom:(UIViewController *) vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self getVisibleViewControllerFrom:[((UINavigationController *) vc) visibleViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self getVisibleViewControllerFrom:[((UITabBarController *) vc) selectedViewController]];
    } else {
        if (vc.presentedViewController) {
            return [self getVisibleViewControllerFrom:vc.presentedViewController];
        } else {
            return vc;
        }
    }
}


@end
